package com.dcivision.framework.taglib.channel;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.jsp.PageContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;

public class AjaxChannelFormatterAdapter {

  private static final Log log = LogFactory.getLog(AjaxChannelFormatterAdapter.class);

  public static AbstractAjaxChannelFormatter getAjaxChannelFormatter(PageContext pageContext,int pageSize,List channelList,String channelName) throws ClassNotFoundException{
    return getAjaxChannelFormatterByChannelName(pageContext,pageSize,channelList,channelName); 
  }
  
  private static AbstractAjaxChannelFormatter getAjaxChannelFormatterByClassName(PageContext pageContext,int pageSize,List channelList,String className) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
    Class[] params = new Class[]{PageContext.class,int.class,List.class};
    Object[] paramValues = new Object[]{pageContext,new Integer(pageSize),channelList};
    Constructor constructor=Class.forName(className).getConstructor(params);
    return (AbstractAjaxChannelFormatter)constructor.newInstance(paramValues);  
  }
  
  private static AbstractAjaxChannelFormatter getAjaxChannelFormatterByChannelName(PageContext pageContext,int pageSize,List channelList,String channelName) throws ClassNotFoundException{
    String className = "com.dcivision.framework.taglib.channel.";
    String preference = ((SessionContainer)pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY)).getPreference();
    
    if(AjaxConstant.MEETINGFILTER.equalsIgnoreCase(channelName)){
      className +="AjaxMeetingFormatter_"+preference;
    }else if(AjaxConstant.MESSAGEINBOXFILTER.equalsIgnoreCase(channelName)){
      className +="AjaxMessageFormatter_"+preference;
    }else if(AjaxConstant.PROGRESSMONITORFILTER.equalsIgnoreCase(channelName)){
      className +="AjaxTrackingFormatter_"+preference;
    }else if(AjaxConstant.RECENTDOCFILTER.equalsIgnoreCase(channelName)){
      className +="AjaxRecentDocFormatter_"+preference;
    }else if(AjaxConstant.TASKINBOXFILTER.equalsIgnoreCase(channelName)){
      className +="AjaxTaskInboxFormatter_"+preference;
    }
    try{
      return getAjaxChannelFormatterByClassName(pageContext,pageSize,channelList,className);
    }catch(Exception ex){
      log.error(ex, ex);
      throw new ClassNotFoundException("Not find the AjaxContent fit to the Preference and channelName given. ", ex);
    }
  }
}
